package org.jeecg.modules.flowermater.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.flower.entity.FlowerStorehouse;
import org.jeecg.modules.flower.service.IFlowerStorehouseService;
import org.jeecg.modules.flower.util.CommonUtil;
import org.jeecg.modules.flowermater.entity.FlowerMaterialIn;
import org.jeecg.modules.flowermater.entity.FlowerMaterialInMain;
import org.jeecg.modules.flowermater.service.IFlowerMaterialBookService;
import org.jeecg.modules.flowerutil.PeriodUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.def.TemplateExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flowermater.entity.FlowerMaterialOut;
import org.jeecg.modules.flowermater.entity.FlowerMaterialOutMain;
import org.jeecg.modules.flowermater.vo.FlowerMaterialOutMainPage;
import org.jeecg.modules.flowermater.service.IFlowerMaterialOutMainService;
import org.jeecg.modules.flowermater.service.IFlowerMaterialOutService;
import org.jeecgframework.poi.excel.view.JeecgTemplateExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 采后物资出库主表
 * @Author: jeecg-boot
 * @Date:   2022-07-13
 * @Version: V1.0
 */
@Api(tags="采后物资出库主表")
@RestController
@RequestMapping("/flowermater/flowerMaterialOutMain")
@Slf4j
public class FlowerMaterialOutMainController {
	@Autowired
	private IFlowerMaterialOutMainService flowerMaterialOutMainService;
	@Autowired
	private IFlowerMaterialOutService flowerMaterialOutService;

	 @Autowired
	 private IFlowerStorehouseService flowerStorehouseService;

	 @Autowired
	 private IFlowerMaterialBookService flowerMaterialBookService;

	 @Autowired
	 private ISysDictService sysDictService;
	 @Autowired
	 private ISysUserService sysUserService;
	 @Value("${yth.tempMaterExcelout}")
	 private  String tempExcelout;
	 /**
	 * 分页列表查询
	 *
	 * @param flowerMaterialOutMain
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "采后物资出库主表-分页列表查询")
	@ApiOperation(value="采后物资出库主表-分页列表查询", notes="采后物资出库主表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(FlowerMaterialOutMain flowerMaterialOutMain,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req,
								   @RequestParam(value = "sDate",defaultValue = "") String sDate ,
								   @RequestParam(value = "eDate",defaultValue = "") String eDate) {
		QueryWrapper<FlowerMaterialOutMain> queryWrapper = QueryGenerator.initQueryWrapper(flowerMaterialOutMain, req.getParameterMap());
		Page<FlowerMaterialOutMain> page = new Page<FlowerMaterialOutMain>(pageNo, pageSize);
		queryWrapper.orderByDesc("out_time");
		queryWrapper.orderByDesc("no");
		if(StringUtils.isNotBlank(sDate)){
			queryWrapper.ge("out_time",sDate);
		}
		if(StringUtils.isNotBlank(eDate)){
			queryWrapper.le("out_time",eDate+" 23:59:59");
		}

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		queryWrapper.inSql("storehouse", "select b.code from flower_storehouse b , flower_storehouse_detail c " +
				"where b.id = c.mainid  and flower_material_out_main.storehouse = b.code " +
				"and personid = '"+sysUser.getId()+"'");
//		queryWrapper.exists("select 1 from flower_storehouse b , flower_storehouse_detail c " +
//				"where b.id = c.mainid  and flower_material_out_main.storehouse = b.code " +
//				"and personid = '"+sysUser.getId()+"'");
		IPage<FlowerMaterialOutMain> pageList = flowerMaterialOutMainService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param flowerMaterialOutMainPage
	 * @return
	 */
	@AutoLog(value = "采后物资出库主表-添加")
	@ApiOperation(value="采后物资出库主表-添加", notes="采后物资出库主表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody FlowerMaterialOutMainPage flowerMaterialOutMainPage) {
		FlowerMaterialOutMain flowerMaterialOutMain = new FlowerMaterialOutMain();
		BeanUtils.copyProperties(flowerMaterialOutMainPage, flowerMaterialOutMain);

		//自动生成出库单号
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String dateNo = simpleDateFormat.format(new Date());
//		String refex = "MCK" + dateNo;
		String refex = "CK-CHWZ-" + dateNo;
		LambdaQueryWrapper<FlowerMaterialOutMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.like(FlowerMaterialOutMain::getNo, refex);
		lambdaQueryWrapper.orderByDesc(FlowerMaterialOutMain::getNo);
		List<FlowerMaterialOutMain> list = flowerMaterialOutMainService.list(lambdaQueryWrapper);
		String oldNo = "";
		if (list.size() > 0) {
			oldNo = list.get(0).getNo();
		}
		String no1 = CommonUtil.getNo("CK-CHWZ-", oldNo, 3);
		flowerMaterialOutMain.setNo(no1);
		String storehouse = flowerMaterialOutMain.getStorehouse();
		if( StringUtils.isNotBlank(storehouse)){
			LambdaQueryWrapper<FlowerStorehouse> queryWrapper =new LambdaQueryWrapper<>();
			queryWrapper.eq(FlowerStorehouse::getCode,storehouse);
			FlowerStorehouse one = flowerStorehouseService.getOne(queryWrapper);
			String cost = one.getCost();
			flowerMaterialOutMain.setCost(cost);
		}

		flowerMaterialOutMainService.saveMain(flowerMaterialOutMain, flowerMaterialOutMainPage.getFlowerMaterialOutList());
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param flowerMaterialOutMainPage
	 * @return
	 */
	@AutoLog(value = "采后物资出库主表-编辑")
	@ApiOperation(value="采后物资出库主表-编辑", notes="采后物资出库主表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody FlowerMaterialOutMainPage flowerMaterialOutMainPage) {
		FlowerMaterialOutMain flowerMaterialOutMain = new FlowerMaterialOutMain();
		BeanUtils.copyProperties(flowerMaterialOutMainPage, flowerMaterialOutMain);
		FlowerMaterialOutMain flowerMaterialOutMainEntity = flowerMaterialOutMainService.getById(flowerMaterialOutMain.getId());
		if(flowerMaterialOutMainEntity==null) {
			return Result.error("未找到对应数据");
		}
		String storehouse = flowerMaterialOutMain.getStorehouse();
		if( StringUtils.isNotBlank(storehouse)){
			LambdaQueryWrapper<FlowerStorehouse> queryWrapper =new LambdaQueryWrapper<>();
			queryWrapper.eq(FlowerStorehouse::getCode,storehouse);
			FlowerStorehouse one = flowerStorehouseService.getOne(queryWrapper);
			String cost = one.getCost();
			flowerMaterialOutMain.setCost(cost);
		}
		flowerMaterialOutMainService.updateMain(flowerMaterialOutMain, flowerMaterialOutMainPage.getFlowerMaterialOutList());
		return Result.ok("编辑成功!");
	}

	 /**
	  *  领导确认
	  *
	  * @param    flowerMaterialOutMain
	  * @return
	  */
	 @AutoLog(value = "采后物资出库主表-领导确认")
	 @ApiOperation(value="采后物资出库主表-领导确认", notes="采后物资出库主表-领导确认")
	 @PutMapping(value = "/leaderSure")
	 @Transactional
	 public Result<?> leaderSure(@RequestBody  FlowerMaterialOutMain flowerMaterialOutMain) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

		 FlowerMaterialOutMain flowerMaterialInMainEntity = flowerMaterialOutMainService.getById(flowerMaterialOutMain.getId());
		 if(flowerMaterialInMainEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 if(flowerMaterialOutMain.getState() != 0){
			 if(flowerMaterialOutMain.getState()==1){
				 throw new RuntimeException("领导已经确认");
			 }else if(flowerMaterialOutMain.getState()==2){
				 throw new RuntimeException("库管已经确认");
			 }else
				 throw new RuntimeException("不满足领导确认条件");
		 }

		 String id = flowerMaterialOutMain.getId();
		 FlowerMaterialOutMain flowerMaterialOutMainNew = new FlowerMaterialOutMain();
		 flowerMaterialOutMainNew.setId(id);
		 flowerMaterialOutMainNew.setLeaderSureUser(sysUser.getRealname());
		 flowerMaterialOutMainNew.setLeaderSuretime(new Date());
		 flowerMaterialOutMainNew.setState(1);
		 flowerMaterialOutMainService.updateById(flowerMaterialOutMainNew);

		 return Result.ok("领导确认成功!");
	 }
	 /**
	  *  取消领导确认
	  *
	  * @param    flowerMaterialOutMain
	  * @return
	  */
	 @AutoLog(value = "采后物资出库主表-取消领导确认")
	 @ApiOperation(value="采后物资出库主表-取消领导确认--更新库存", notes="采后物资出库主表-取消领导确认")
	 @PutMapping(value = "/leaderSureBack")
	 @Transactional
	 public Result<?> leaderSureBack(@RequestBody FlowerMaterialOutMain flowerMaterialOutMain) {

		 FlowerMaterialOutMain flowerMaterialInMainEntity = flowerMaterialOutMainService.getById(flowerMaterialOutMain.getId());
		 if(flowerMaterialInMainEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 if(flowerMaterialOutMain.getState() != 1) {
			 if (flowerMaterialOutMain.getState() == 0) {
				 throw new RuntimeException("领导还未确认");
			 } else if (flowerMaterialOutMain.getState() == 2) {
				 throw new RuntimeException("库管已经确认");
			 } else
				 throw new RuntimeException("请领导进行先确认！才能取消！");
		 }
		 String id = flowerMaterialOutMain.getId();
		 FlowerMaterialOutMain flowerMaterialOutMainNew = new FlowerMaterialOutMain();
		 flowerMaterialOutMainNew.setId(id);
		 flowerMaterialOutMainNew.setLeaderSureUser( "");
		 flowerMaterialOutMainNew.setLeaderSuretime(null);
		 flowerMaterialOutMainNew.setState(0);
		 flowerMaterialOutMainService.updateById(flowerMaterialOutMainNew);
		 return Result.ok("库管取消确认成功!");
	 }
	 /**
	  *
	  * k库管审核
	  * @param flowerMaterialOutMain
	  * @return
	  */
	 @AutoLog(value = "采后物资出库主表-库管审核")
	 @ApiOperation(value="采后物资出库主表-库管审核-- --更新库存", notes="采后物资出库主表- --库管审核--更新库存")
	 @PutMapping(value = "/houseSure")
	 @Transactional
	 public Result<?> houseSure(@RequestBody FlowerMaterialOutMain flowerMaterialOutMain) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

		 if(flowerMaterialOutMain.getState() != 1){
			 if(flowerMaterialOutMain.getState()==0){
				 throw new RuntimeException("领导还未确认，请领导进行先确认！财务才能复核！");
			 }else if(flowerMaterialOutMain.getState()==2){
				 throw new RuntimeException("库管已经确认，请先取消");
			 }else
				 throw new RuntimeException("不满足库管确认条件");
		 }
		 String id = flowerMaterialOutMain.getId();
		 FlowerMaterialOutMain flowerMaterialOutMainNew = new FlowerMaterialOutMain();
		 flowerMaterialOutMainNew.setId(id);
		 flowerMaterialOutMainNew.setHouseSureUser(sysUser.getRealname());
		 flowerMaterialOutMainNew.setHouseSuretime(new Date());
		 flowerMaterialOutMainNew.setState(2);
		 if(flowerMaterialOutMain.getLeaderSuretime()!=null){
			 flowerMaterialOutMainNew.setLeaderSuretime(flowerMaterialOutMain.getLeaderSuretime());
		 }
		 flowerMaterialOutMainService.updateById(flowerMaterialOutMainNew);

		 //扣减库存
		 List<FlowerMaterialOut> flowerMaterialOutList= flowerMaterialOutService.selectByMainId(id);
		 flowerMaterialBookService.createOutBooks(flowerMaterialOutMain, flowerMaterialOutList);

		 return Result.ok("财务复核成功!");
	 }
	 /**
	  *
	  * 取消k库管审核
	  * @param flowerMaterialOutMain
	  * @return
	  */
	 @AutoLog(value = "采后物资出库主表- --取消库管审核--更新库存")
	 @ApiOperation(value="采后物资出库主表- --取消库管审核--更新库存", notes="采后物资出库主表- --取消库管审核--更新库存")
	 @PutMapping(value = "/houseSureBack")
	 @Transactional
	 public Result<?> houseSureBack(@RequestBody FlowerMaterialOutMain flowerMaterialOutMain) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

		 if(flowerMaterialOutMain.getState() != 2){
			 if(flowerMaterialOutMain.getState()==0){
				 throw new RuntimeException("领导还未确认，请领导进行先确认！财务才能复核！");
			 }else if(flowerMaterialOutMain.getState()==1){
				 throw new RuntimeException("库管还未确认，请先确认");
			 }else {
				 throw new RuntimeException("不满足取消库管审核条件");
			 }
		 }
		 String id = flowerMaterialOutMain.getId();
		 FlowerMaterialOutMain flowerMaterialInMainNew = new FlowerMaterialOutMain();
		 flowerMaterialInMainNew.setId(id);
		 flowerMaterialInMainNew.setHouseSureUser( "");
		 flowerMaterialInMainNew.setHouseSuretime( null);
		 flowerMaterialInMainNew.setState(1);
		 if(flowerMaterialOutMain.getLeaderSuretime()!=null){
			 flowerMaterialInMainNew.setLeaderSuretime(flowerMaterialOutMain.getLeaderSuretime());
		 }
		 flowerMaterialOutMainService.updateById(flowerMaterialInMainNew);
		 //归还库存
		 flowerMaterialBookService.backOutBooks(flowerMaterialOutMain.getId());
		 return Result.ok("取消库管审核成功!");
	 }

	 /**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采后物资出库主表-通过id删除")
	@ApiOperation(value="采后物资出库主表-通过id删除", notes="采后物资出库主表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		flowerMaterialOutMainService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "采后物资出库主表-批量删除")
	@ApiOperation(value="采后物资出库主表-批量删除", notes="采后物资出库主表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.flowerMaterialOutMainService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采后物资出库主表-通过id查询")
	@ApiOperation(value="采后物资出库主表-通过id查询", notes="采后物资出库主表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		FlowerMaterialOutMain flowerMaterialOutMain = flowerMaterialOutMainService.getById(id);
		if(flowerMaterialOutMain==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(flowerMaterialOutMain);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采后物资出库子表通过主表ID查询")
	@ApiOperation(value="采后物资出库子表主表ID查询", notes="采后物资出库子表-通主表ID查询")
	@GetMapping(value = "/queryFlowerMaterialOutByMainId")
	public Result<?> queryFlowerMaterialOutListByMainId(@RequestParam(name="id",required=true) String id) {
		List<FlowerMaterialOut> flowerMaterialOutList = flowerMaterialOutService.selectByMainId(id);
		return Result.ok(flowerMaterialOutList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param flowerMaterialOutMain
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FlowerMaterialOutMain flowerMaterialOutMain,
								  @RequestParam(value = "sDate",defaultValue = "") String sDate ,
								  @RequestParam(value = "eDate",defaultValue = "") String eDate) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<FlowerMaterialOutMain> queryWrapper = QueryGenerator.initQueryWrapper(flowerMaterialOutMain, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		queryWrapper.orderByAsc("out_time");
		queryWrapper.orderByAsc("no");
		if(StringUtils.isNotBlank(sDate)){
			queryWrapper.ge("out_time",sDate);
		}
		if(StringUtils.isNotBlank(eDate)){
			queryWrapper.le("out_time",eDate+" 23:59:59");
		}
      //Step.2 获取导出数据
      List<FlowerMaterialOutMain> queryList = flowerMaterialOutMainService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<FlowerMaterialOutMain> flowerMaterialOutMainList = new ArrayList<FlowerMaterialOutMain>();
      if(oConvertUtils.isEmpty(selections)) {
          flowerMaterialOutMainList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          flowerMaterialOutMainList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<FlowerMaterialOutMainPage> pageList = new ArrayList<FlowerMaterialOutMainPage>();
      for (FlowerMaterialOutMain main : flowerMaterialOutMainList) {
          FlowerMaterialOutMainPage vo = new FlowerMaterialOutMainPage();
          BeanUtils.copyProperties(main, vo);
          List<FlowerMaterialOut> flowerMaterialOutList = flowerMaterialOutService.selectByMainId(main.getId());
          vo.setFlowerMaterialOutList(flowerMaterialOutList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "采后物资出库主表列表");
      mv.addObject(NormalExcelConstants.CLASS, FlowerMaterialOutMainPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("采后物资出库主表数据", "导出人:"+sysUser.getRealname(), "采后物资出库主表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<FlowerMaterialOutMainPage> list = ExcelImportUtil.importExcel(file.getInputStream(), FlowerMaterialOutMainPage.class, params);
              for (FlowerMaterialOutMainPage page : list) {
                  FlowerMaterialOutMain po = new FlowerMaterialOutMain();
                  BeanUtils.copyProperties(page, po);
                  flowerMaterialOutMainService.saveMain(po, page.getFlowerMaterialOutList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }


	 /**
	  *
	  * 导出excel入库单
	  *
	  * @param request
	  * @param flowerMaterialOutMain
	  * @return
	  */
	 @RequestMapping(value = "/exportXlsForTemp")
	 @ApiOperation(value="导出excel入库单-导出excel入库单", notes="导出excel入库单-导出excel入库单")
	 public ModelAndView exportXlsForTemp(HttpServletRequest request,   FlowerMaterialOutMain flowerMaterialOutMain) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy/MM/dd");
		 if(StringUtils.isBlank(tempExcelout)){
			 throw new RuntimeException("还未配置入库单模板，请联系管理员配置入库单模板");
		 }
		 TemplateExportParams params   = new TemplateExportParams(tempExcelout);//模板

		 String id = flowerMaterialOutMain.getId();
		 FlowerMaterialOutMain inMain = flowerMaterialOutMainService.getById(id);

		 String cost = inMain.getCost();
		 String storehouse2 = inMain.getStorehouse();
		 String storehouseName = "";
		 String costName = "";
		 if(StringUtils.isNotBlank(cost)  ){
			 String name = sysDictService.queryDictTextByKey("ch_cost", cost);
			 costName = name ;
		 }
		 if( StringUtils.isNotBlank(storehouse2) ){
			 QueryWrapper<FlowerStorehouse> queryWrapper2=new QueryWrapper<>();
			 queryWrapper2.eq("code", storehouse2 );
			 FlowerStorehouse house = flowerStorehouseService.getOne(queryWrapper2);
			 storehouseName = house.getName();
		 }
		 String no="";
		 if(StringUtils.isNotBlank(inMain.getNo())){
			 no = inMain.getNo() ;
		 }
//		 String sourceGreenhouse = "";
//		 if(StringUtils.isNotBlank(tagInMain2.getSourceGreenhouse()) ){
//			 FlowerPlantingGreenhouse greenhouse = greenhouseService.getById(tagInMain2.getSourceGreenhouse());
//			 sourceGreenhouse  = greenhouse.getName();
//		 }

		 Map<String, Object> map = new HashMap<String, Object>();
		 map.put("sortTime", simpleDateFormat.format(inMain.getOutTime()));
		 map.put("cost", costName);
		 map.put("storehouse", storehouseName);
		 map.put("no", no);

		 map.put("houseSureUser", inMain.getHouseSureUser());
		 SysUser user = sysUserService.getUserByName(inMain.getCreateBy());
		 map.put("createby", user.getRealname());
		 map.put("leaderUser", inMain.getLeaderSureUser());

		 List<FlowerMaterialOut> detalList = flowerMaterialOutService.selectByMainId(id);

		 if(detalList.size()==0){
			 throw new RuntimeException("没有入库详情不能生成入库单");
		 }
		 List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
		 BigDecimal countPrice =new BigDecimal("0");
		 Double countNum = Double.parseDouble("0");

		 for(FlowerMaterialOut materialOut : detalList){
			 Map<String, Object> lm = new HashMap<String, Object>();

			 lm.put("name", materialOut.getName() );
			 lm.put("code", materialOut.getCode() );
			 lm.put("specs", materialOut.getSpecs() );
			 lm.put("unitMeasure", materialOut.getUnitMeasure() );
			 lm.put("price", materialOut.getPrice() );
			 BigDecimal totalPrice =new BigDecimal("0");
			 Double num = Double.parseDouble("0");
			 if(materialOut.getTotalPrice()!=null){
				 totalPrice = materialOut.getTotalPrice() ;
			 }
			 if(materialOut.getNum()!=null){
				 num = materialOut.getNum() ;
			 }
			 lm.put("num", num );
			 lm.put("totalPrice", totalPrice );

			 countNum += num ;//计算数量合计
			 countPrice = countPrice.add(totalPrice);
			 listMap.add(lm);
		 }
		 if(detalList.size()==1){
			 Map<String, Object> lm = new HashMap<String, Object>();
			 listMap.add(lm);
		 }
		 map.put("sumNumber",countNum);
		 map.put("sumtotalPrice",countPrice);
		 map.put("maplist", listMap);

		 ModelAndView mv2 = new ModelAndView(new JeecgTemplateExcelView());
		 mv2.addObject(TemplateExcelConstants.PARAMS,params);
		 mv2.addObject(TemplateExcelConstants.MAP_DATA,map);
		 return mv2;
	 }

 }
